<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import { io, type Socket } from 'socket.io-client'
import { onMounted, onUnmounted, ref, nextTick } from 'vue'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import type { TimeMessages, Message } from '@/types/room'
import { MsgType } from '@/enums'
import { getConsultOrderDetail } from '@/services/consult'
import type { ConsultOrderItem, Image } from '@/types/consult'
import { showToast } from 'vant'
import { provide } from 'vue'

const store = useUserStore()
const route = useRoute()

const list = ref<Message[]>([])

const time = ref()
const first = ref(true)

let ws: Socket
onMounted(() => {
  // 创建websocket连接
  ws = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}` // 验证身份信息
    },
    query: {
      orderId: route.query.orderId
    }
  }) // 创建ws实例

  ws.on('connect', () => {
    console.log('链接成功')
    list.value = [] // 如果重新连接了 那么清空聊天记录
  })

  ws.on('error', () => {
    console.log('失败了')
  })

  ws.on('disconnect', () => {
    console.log('断开连接拉')
  })

  // 默认的消息列表 / 更早的消息也是这个事件
  ws.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    // 消息按照时间节点 一段一段的  转换成 一个个消息
    console.log(data, 888)
    // [ {一段消息} ]
    const arr: Message[] = []

    data.forEach((item: TimeMessages, index: number) => {
      if (index === 0) {
        // 这一段的消息是最早 就应该记录他的时间
        time.value = item.createTime
      }
      // 将每段消息转换成一个普通消息
      arr.push({
        msgType: MsgType.Notify,
        msg: { content: item.createTime },
        createTime: item.createTime,
        id: item.createTime
      })

      // item.items.forEach((v: any) => {
      //   arr.push(v)
      // })
      arr.push(...item.items)
    })
    console.log(arr, 999)

    // list.value = arr
    list.value.unshift(...arr) // 往数组最前添加更多数据

    // loading.value = false

    if (!data.length) {
      showToast('暂无更早的聊天记录')
      return
    }

    nextTick(() => {
      // 第一次进入页面??
      if (first.value) {
        // 把默认拿到的消息全部已读  给数组中最后一个消息的id传到后端
        ws.emit('updateMsgStatus', arr[arr.length - 1].id)
        // 视图更新后触发
        window.scrollTo(0, document.body.scrollHeight)
        first.value = false
      }
    })
  })

  // 订单状态变化
  ws.on('statusChange', async () => {
    // 订单状态变化时
    console.log(222)

    const res = await getConsultOrderDetail(route.query.orderId as string)
    // console.log(first)
    consult.value = res.data
  })

  // 收消息(自己的消息+医生的消息)
  ws.on('receiveChatMsg', (e) => {
    // console.log(e)
    list.value.push(e) // 接收消息 存储消息 => 数据多了 => 结构变长(异步)  nextTick

    nextTick(() => {
      ws.emit('updateMsgStatus', e.id)
      // 视图更新后触发
      window.scrollTo(0, document.body.scrollHeight)
    })
  })
})

onUnmounted(() => {
  ws.close()
})

// ------------------------------------------------------
const consult = ref<ConsultOrderItem>() // 这个是订单详情数据 里面有医生id 订单id...
onMounted(async () => {
  // 带着orderId 请求后端接口
  // console.log('获取订单的状态') // 等待 咨询中 已结束

  const res = await getConsultOrderDetail(route.query.orderId as string)
  // console.log(first)
  consult.value = res.data
})

const send = (str: string) => {
  // 发送给后端 => 数据是有格式要求的
  // ws.emit('sendChatMsg', str)
  ws.emit('sendChatMsg', {
    from: store.user?.id, // 发消息的人id
    to: consult.value?.docInfo?.id, // 收消息的人id
    msgType: MsgType.MsgText, // 消息类型: 文字
    msg: { content: str } // 消息的内容
  })
}
const send2 = (img: Image) => {
  // 子组件上传好了照片 交给父组件 => emit发送消息给后段
  ws.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: { picture: img }
  })
}
// -------------------------下拉刷新-------------------------------------------------------
const loading = ref(false) // 不在下拉刷新
const onRefresh = () => {
  // setTimeout(() => {
  // console.log('加载更多数据')
  ws.emit('getChatMsgList', 20, time.value, route.query.orderId) // 触发一个事件 获取更多数据
  loading.value = false // 只要下拉 会自动将loading改true  需要你在数据获取后改false
  // }, 4000)
}

// -----------------------consult订单详情数据跨级传递--------------------------
provide('consult', consult)

provide('updateList', (score: number) => {
  const temp = list.value.find((item) => item.msgType === MsgType.CardEvaForm)
  if (temp) {
    temp.msgType = MsgType.CardEva
    // 已经评价后 会有这个字段 且有一个score分数
    temp.msg.evaluateDoc = {
      score: score
    }
  }
})
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="医生问诊室" />
    <room-status :status="consult?.status" :countdown="consult?.countdown" />
    <!-- <router-link to="/home">首页</router-link> -->
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <!-- 检测是否处于下拉刷新状态 -->
      <RoomMessage :list="list"></RoomMessage>
    </van-pull-refresh>
    <RoomAction
      @send-text="send"
      @send-image="send2"
      :disabled="consult?.status !== 3"
    ></RoomAction>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
